//@Author: cyl
//@File: main.go
//@Time: 2022/06/09 10:19:53
package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
)

type Reader struct {
	io.Reader
	Total   int64 // 总文件大小
	Current int64 // 当前下载进度
}

func (r *Reader) Read(p []byte) (n int, err error) {
	n, err = r.Reader.Read(p)
	r.Current += int64(n) // 计算当前进度
	fmt.Printf("\r下载进度:%.2f%%", float64(r.Current*100/r.Total))
	return
}

func DownloadFileProcess(url, filename string) {
	r, err := http.Get(url)
	if err != nil {
		panic(err)
	}
	defer r.Body.Close()

	f, f_err := os.Create(filename)
	if f_err != nil {
		panic(f_err)
	}
	defer f.Close()

	reader := &Reader{
		Reader: r.Body,
		Total:  r.ContentLength,
	}
	n, err := io.Copy(f, reader)
	fmt.Println(n, err)
}

func main() {
	url := "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg1.qunarzz.com%2Ftravel%2Fd9%2F1612%2F57%2F6882c14f9db100b5.jpg_r_720x480x95_5dab1eb2.jpg&refer=http%3A%2F%2Fimg1.qunarzz.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1657334518&t=01768df4e1fc5ec67db668c121246ffe"
	filename := "covr.png"
	DownloadFileProcess(url, filename)
}
